<?php
# 导入数据库接口文件
require_once 'dr-app-config.php';
require_once 'dr-app-functions.php';
require_once 'dr-db-reputations.php';

# 获得用户的请求
$action = isset($_POST['action']) ? $_POST['action'] : '';
//$action = 'mark_question';
switch ($action) {

	case 'ask_question':
		echo dr_ask_question();
		break;

	case 'reply_question':
		echo dr_reply_question();
		break;

	case 'get_question_list':
		echo dr_get_question_list();
		break;

	case 'get_question_detail':
		echo dr_get_question_detail();
		break;

	case 'mark_question':
		echo dr_mark_question();
		break;

	case 'set_best_answer':
		echo dr_set_best_answer();
		break;
	case 'get_everyday_num':
		echo dr_get_everyday_questionnum();
		break;

	case 'get_searched_questions_with_ids':
		echo get_searched_questions_with_ids();
		break;

	default:
		echo '';
}

/**
 * 提问
 */
function dr_ask_question()
{
	global $db;
	//获得请求参数
	$user_id = $_POST['user_id'];
	$title = $_POST['title'];
	$content = $_POST['content'];
	$tags = explode(" ", trim($_POST['tags']));
	$is_mail = !empty($_POST['is_mail']) ? 1 : 0;
	$type = 'Q';

	//将问题相关数据插入数据库
	$result = dr_db_query_sub($db,
							  'INSERT INTO ^questions (user_id, title, content, is_mail,created_date, updated_date)' .
							  'VALUES ($,$,$,$,date_add(NOW(),interval 8 hour),date_add(NOW(),interval 8 hour))', $user_id, $title, $content, $is_mail);
	if (false === $result) {
		return '{"id":-1}';
	}

	//获得question_id
	$question_id = dr_db_last_insert_id($db);
	$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,$,date_add(NOW(),interval 8 hour),#)', $user_id, $type, $question_id);

	if (false === $result) {
		return '{"id":-2}';
	}

	/********************************发送消息到给收听的用户********************************************/
	$listeners = dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_people where marked_user_id=#', $user_id));
	foreach ($listeners as $listener_id)
	{
		$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
									   ' values(#,#,#,\'MPQ\',date_add(NOW(),interval 8 hour))', $listener_id, $user_id, $question_id);
		if (false == $result) {
			return '{"id":-3}';
		}
	}

	//当tag为空的时候
	if ($tags[0] == '') {
		return '{"id":' . $question_id . '}';
		//return '{"id":5}';
	}

	//更新tags表
	foreach ($tags as $tag_title)
	{
		//如果没有目标tag，就在tags表中增加这个tag
		$result = dr_db_query_sub($db,
								  'SELECT tag_id,title,question_num FROM ^tags WHERE title = $', $tag_title);
		if (false === $result) {
			return '{"id":-7}';
		}

		if (0 == mysql_num_rows($result)) {
			$result = dr_db_query_sub($db, 'INSERT INTO ^tags (title, question_num)' .
										   'VALUES ($, 0)', $tag_title);
			if (false === $result) {
				return '{"id":-8}';
			}
			$question_num = 0;
			$tag_id = dr_db_last_insert_id($db);
		}
		else
		{
			$result_array = dr_db_read_one_assoc($result);
			$tag_id = $result_array['tag_id'];
			$question_num = $result_array['question_num'];
		}
		//tags表的question_num需要自增
		$question_num++;

		//更新question_num
		$result = dr_db_query_sub($db,
								  'UPDATE ^tags SET question_num = $ WHERE tag_id = $', $question_num, $tag_id);
		if (false === $result) {
			return '{"id":-9}';
		}

		//将问题和标签的关系插入表question_tag
		$result = dr_db_query_sub($db, 'INSERT INTO ^question_tag (question_id, tag_id)' .
									   'VALUES ($,$)', $question_id, $tag_id);
		if (false === $result) {
			return '{"id":-10}';
		}


	}
	# 更新用户的积分
	$result = dr_db_update_user_reputation($user_id, 'question_send');
	echo '{"id":' . $question_id . '}';
}

function dr_reply_question()
{
	global $db;

	//获得请求参数
	$user_id = $_POST['user_id'];
	$question_id = $_POST['question_id'];
	$parent_id = $_POST['parent_id'];
	$content = $_POST['content'];
	$type = $_POST['type'];

	$result = dr_db_query_sub($db,
							  'INSERT INTO ^replies (user_id, question_id, parent_id, content, type, created_date, updated_date)' .
							  'VALUES ($,$,$,$,$,date_add(NOW(),interval 8 hour),date_add(NOW(),interval 8 hour))', $user_id, $question_id, $parent_id, $content, $type);
	if (false === $result) {
		return;
	}

	//将历史记录插入动作历史记录表中
	$reply_id = dr_db_last_insert_id($db);
	if ('A' == $type)
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,$,date_add(NOW(),interval 8 hour),#)', $user_id, $type, $question_id);
	else if ('C' == $type)
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,$,date_add(NOW(),interval 8 hour),#)', $user_id, $type, $reply_id);
	if (false === $result) {
		return;
	}

	//如果类型是回答，则更新questions表的answers_num域
	if ('A' == $type) {
		//更新questions表的answers_num域
		$result = dr_db_query_sub($db,
								  'SELECT answers_num FROM ^questions WHERE question_id = $', $question_id);
		if (false === $result) {
			return;
		}
		$answers_num = dr_db_read_one_value($result);
		$answers_num++;
		$result = dr_db_query_sub($db,
								  'UPDATE ^questions SET answers_num = $ WHERE question_id = $', $answers_num, $question_id);
		if (false === $result) {
			return;
		}
	}

	//如果是回答：发送消息给相应的用户和关注用户
	if ('A' == $type) {
		//发送消息给问题属主
		$owner_id = dr_db_read_one_value(dr_db_query_sub($db, 'select user_id from ^questions where question_id=#', $question_id));
		$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
									   ' values(#,#,#,\'AQ\',date_add(NOW(),interval 8 hour))', $owner_id, $user_id, $question_id);

		//发送消息给问题关注者
		$mark_array = dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_question where question_id=#', $question_id));
		foreach ($mark_array as $owner_id)
		{
			$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
										   ' values(#,#,#,\'AM\',date_add(NOW(),interval 8 hour))', $owner_id, $user_id, $question_id);
		}

		/************************************发送消息给该用户的收听者**********************************************/
		$listeners = dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_people where marked_user_id=#', $user_id));
		foreach ($listeners as $listener_id)
		{
			$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
										   ' values(#,#,#,\'MPA\',date_add(NOW(),interval 8 hour))', $listener_id, $user_id, $question_id);
		}
	}

	//如果是评论：发送消息给相应的用户、回答者和关注者
	if ('C' == $type) {
		//发送消息给问题属主
		$owner_id = dr_db_read_one_value(dr_db_query_sub($db, 'select user_id from ^questions where question_id=#', $question_id));
		$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
									   ' values(#,#,#,\'CQ\',date_add(NOW(),interval 8 hour))', $owner_id, $user_id, $question_id);

		//发送消息给对应的回答者
		$owner_id = dr_db_read_one_value(dr_db_query_sub($db, 'select user_id from ^replies where reply_id=# and type=\'A\'', $parent_id));
		if ($owner_id)
			$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
										   ' values(#,#,#,\'CA\',date_add(NOW(),interval 8 hour))', $owner_id, $user_id, $question_id);

		//发送消息给问题的关注者
		$mark_array = dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_question where question_id=#', $question_id));
		foreach ($mark_array as $owner_id)
		{
			$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
										   ' values(#,#,#,\'CM\',date_add(NOW(),interval 8 hour))', $owner_id, $user_id, $question_id);
		}

		/************************************发送消息给该用户的收听者**********************************************/
		$listeners = dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_people where marked_user_id=#', $user_id));
		foreach ($listeners as $listener_id)
		{
			$result = dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)' .
										   ' values(#,#,#,\'MPC\',date_add(NOW(),interval 8 hour))', $listener_id, $user_id, $question_id);
		}
	}
	# 更新用户的积分
	switch ($type) {
		case 'A':
			$rep_type = 'answer_send';
			break;
		case 'C':
			$rep_type = 'comment_send';
			break;
		default:
			$rep_type = null;
			break;
	}
	if ($rep_type) {
		$result = dr_db_update_user_reputation($user_id, $rep_type);
	}

	echo '{ret:0}';
}

function dr_get_question_list()
{
	global $db;

	$questions = array();

	$tag_id      = $_POST['tag_id'];
	$list        = $_POST['list'];
	$order       = $_POST['order'];
	$login_id    = $_POST['login_id'];
	$page        = $_POST['page'];

	$question_num = 0;
	$top_question_num = 0;
	$question_page_size = dr_db_get_option('question_per_page');
	switch ($order) {
		case 'answers':
			$order = 'answers_num';
			break;
		case 'marks':
			$order = 'marks_num';
			break;
		case 'votes':
			$order = 'up_votes_num';
			break;
		default:
			$order = 'updated_date';
			break;
	}

	switch ($list) {
		case 'answered':
			$tab_where = 'Q.answers_num > 0';
			break;

		case 'unanswered':
			$tab_where = 'Q.answers_num = 0';
			break;

		case 'bested':
			$tab_where = 'Q.best_answer > 0';
			break;

		case 'unbested':
			$tab_where = 'Q.best_answer = 0';
			break;
		default:
			// do nothing
	}

	if ($tag_id != 0) {
		$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select question_num from ^tags where tag_id=#', $tag_id));
		if (($page - 1) * $question_page_size > $question_num || $page <= 0)
			$page = 1;
		$start = ($page - 1) * $question_page_size;

		if (isset($question_num)) {
			$result = dr_db_query_sub($db,
									  'SELECT Q.*, U.username, U.email, U.points ' .
									  'FROM ^questions Q, ^users U ' .
									  'WHERE Q.user_id = U.user_id AND Q.question_id IN (SELECT question_id FROM ^question_tag WHERE tag_id=#) ' . // tag_id
									  (isset($tab_where) ? "AND $tab_where " : '') .
									  'ORDER BY # DESC ' . // order
									  'LIMIT #,#', $tag_id, $order, $start, $question_page_size); // start questions_pate_size
		}

	} else if (!empty($list)) {

		dr_get_question_rightlist($question_num, $order, $result);
	} else {

		$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions'));
		if (($page - 1) * $question_page_size > $question_num || $page <= 0)
			$page = 1;
		$start = ($page - 1) * $question_page_size;

		$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U C' .
									   ' where Q.user_id=U.user_id order by # desc limit #,#', $order, $start, $question_page_size);

	}

	//读取问题
	while ($row = mysql_fetch_assoc($result)) {
		$question['id'] = $row['question_id'];
		$question['user_id'] = $row['user_id'];
		$question['user_username'] = $row['username'];
		$question['user_points'] = $row['points'];
		$question['title'] = $row['title'];
		$question['content'] = $row['content'];
		$question['user_email'] = $row['email'];
		$question['up_votes_num'] = $row['up_votes_num'];
		$question['down_votes_num'] = $row['down_votes_num'];
		$question['answers_num'] = $row['answers_num'];
		$question['marks_num'] = $row['marks_num'];
		$question['created_date'] = $row['created_date'];

		if ($login_id) {
			$result_mark = dr_db_query_sub($db, 'select * from ^mark_question where user_id=# and question_id=#', $login_id, $question['id']);
			if (mysql_num_rows($result_mark) == 0)
				$question['is_mark'] = false;
			else
				$question['is_mark'] = true;
		}
		else
		{
			$question['is_mark'] = false;
		}

		$result_ex = dr_db_query_sub($db, 'select a.tag_id,title from dr_tags a,dr_question_tag b' .
										  ' where a.tag_id=b.tag_id and question_id=#', $question['id']);
		$tags = array();
		while ($row_ex = mysql_fetch_assoc($result_ex))
		{
			$tag['id'] = $row_ex['tag_id'];
			$tag['title'] = $row_ex['title'];
			array_push($tags, $tag);
		}
		$question['tags'] = $tags;
		array_push($questions, $question);
	}

	//if($question_num/$)
	$pages = array();
	$page_num = ceil($question_num / $question_page_size);
	dr_calc_pages($page, $page_num, $pages);

	/******************************************************/
	$setting['show_day_top'] = dr_db_get_option('display_day_top');
	$setting['show_week_top'] = dr_db_get_option('display_week_top');
	$setting['show_month_top'] = dr_db_get_option('display_month_top');
	$setting['show_all_top'] = dr_db_get_option('display_all_top');

	$question_ex = array();
	$question_ex[0] = $pages;
	$question_ex[1] = $questions;
	$question_ex[2] = $setting;
	$question_ex[3] = $top_question_num;

	echo json_encode($question_ex);
}

function dr_get_question_rightlist(&$question_num, $order, &$result)
{
	global $db;
	$list = $_POST['list'];
	$page = $_POST['page'];

	$question_page_size = dr_db_get_option('question_per_page');

	switch ($list)
	{
		case 'answered':
			$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions where answers_num>0'));
			if (($page - 1) * $question_page_size > $question_num || $page <= 0)
				$page = 1;
			$start = ($page - 1) * $question_page_size;
			$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U' .
										   ' where Q.user_id=U.user_id and Q.answers_num>0 order by # desc limit #,#', $order, $start, $question_page_size);
			break;
		case 'unanswered':
			$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions where answers_num=0'));
			if (($page - 1) * $question_page_size > $question_num || $page <= 0)
				$page = 1;
			$start = ($page - 1) * $question_page_size;
			$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U' .
										   ' where Q.user_id=U.user_id and Q.answers_num=0 order by # desc limit #,#', $order, $start, $question_page_size);
			break;
		case 'bested':
			$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions where best_answer>0'));
			if (($page - 1) * $question_page_size > $question_num || $page <= 0)
				$page = 1;
			$start = ($page - 1) * $question_page_size;
			$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U' .
										   ' where Q.user_id=U.user_id and Q.best_answer>0 order by # desc limit #,#', $order, $start, $question_page_size);
			break;
		case 'unbested':
			$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions where best_answer=0'));
			if (($page - 1) * $question_page_size > $question_num || $page <= 0)
				$page = 1;
			$start = ($page - 1) * $question_page_size;
			$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U' .
										   ' where Q.user_id=U.user_id and Q.best_answer=0 order by # desc limit #,#', $order, $start, $question_page_size);
			break;
		case 'allquestion':
			$question_num = dr_db_read_one_value(dr_db_query_sub($db, 'select count(*) from ^questions'));
			if (($page - 1) * $question_page_size > $question_num || $page <= 0)
				$page = 1;
			$start = ($page - 1) * $question_page_size;
			$result = dr_db_query_sub($db, 'select Q.*,U.username,U.email,U.points from ^questions Q, ^users U' .
										   ' where Q.user_id=U.user_id order by # desc limit #,#', $order, $start, $question_page_size);
			break;
	}
}

function dr_calc_pages($page, $page_num, &$pages)
{
	if ($page_num > 1) {
		if ($page_num < 7) {
			for ($i = 0; $i < $page_num; $i++)
			{
				$page_temp['order'] = $i + 1;
				array_push($pages, $page_temp);
			}
		}
			//>=7
		else
		{
			//12345...9
			if ($page <= 3) {
				for ($i = 0; $i < 5; $i++)
				{
					$page_temp['order'] = $i + 1;
					array_push($pages, $page_temp);
				}
				$page_temp['order'] = '...';
				array_push($pages, $page_temp);
				$page_temp['order'] = $page_num;
				array_push($pages, $page_temp);
			}
				//1...56789
			else if ($page > $page_num - 3) {
				$page_temp['order'] = 1;
				array_push($pages, $page_temp);
				$page_temp['order'] = '...';
				array_push($pages, $page_temp);
				for ($i = $page_num - 5; $i < $page_num; $i++)
				{
					$page_temp['order'] = $i + 1;
					array_push($pages, $page_temp);
				}
			}
				//1...34567...9
			else
			{
				$page_temp['order'] = 1;
				array_push($pages, $page_temp);
				if ($page != 4) {
					$page_temp['order'] = '...';
					array_push($pages, $page_temp);
				}
				for ($i = $page - 3; $i < $page + 2; $i++)
				{
					$page_temp['order'] = $i + 1;
					array_push($pages, $page_temp);
				}
				if ($page != $page_num - 3) {
					$page_temp['order'] = '...';
					array_push($pages, $page_temp);
				}
				$page_temp['order'] = $page_num;
				array_push($pages, $page_temp);
			}
		}
	}
}


function dr_get_question_detail()
{
	global $db;

	$question_id = $_POST['question_id'];
	$login_id = $_POST['login_id'];
	$msg_id = $_POST['msg_id'];
	$order = $_POST['order'];
	$page = $_POST['answer_page'];

	$questions = array();
	$answers = array();
	$result_array = array();
	$pages = array();

	$answer_page_size = dr_db_get_option('answer_per_page');
	$answers_num = dr_db_read_one_value(dr_db_query_sub($db, 'select answers_num from ^questions where question_id=#', $question_id));


	//删除已读消息记录
	if ($msg_id != 0)
		$result = dr_db_query_sub($db, 'delete from ^user_messages where umsg_id=#', $msg_id);

	//读取问题和他的相关信息
	$row = dr_db_read_one_assoc(
        dr_db_query_sub(
            $db,
            'select Q.*,U.username,U.email,U.points ' .
            'from ^questions Q, ^users U where Q.question_id=# and Q.user_id=U.user_id',
            $question_id
        )
    );
	$questions['id'] = $row['question_id'];
	$questions['user_id'] = $row['user_id'];
	$questions['user_username'] = $row['username'];
	$questions['user_email'] = $row['email'];
	$questions['user_points'] = $row['points'];
	$questions['title'] = $row['title'];
	$questions['up_votes_num'] = $row['up_votes_num'];
	$questions['down_votes_num'] = $row['down_votes_num'];
	$questions['marks_num'] = $row['marks_num'];
	$questions['answers_num'] = $row['answers_num'];
	$questions['content'] = $row['content'];
	$questions['created_date'] = $row['created_date'];
	$questions['best_answer'] = $row['best_answer'];

	if ($login_id) {
		$result_mark = dr_db_query_sub($db, 'select * from ^mark_question where user_id=# and question_id=#', $login_id, $question_id);
		if (mysql_num_rows($result_mark) == 0)
			$questions['is_mark'] = false;
		else
			$questions['is_mark'] = true;
	}
	else
		$questions['is_mark'] = false;

	$tags = array();
	$result_ex = dr_db_query_sub($db, 'select a.tag_id,title from dr_tags a,dr_question_tag b' .
									  ' where a.tag_id=b.tag_id and question_id=#', $questions['id']);
	while ($row_ex = mysql_fetch_assoc($result_ex))
	{
		$tag['id'] = $row_ex['tag_id'];
		$tag['title'] = $row_ex['title'];
		array_push($tags, $tag);
	}
	$questions['tags'] = $tags;

	//设置最佳答案
	dr_get_question_best_answer($answers, $questions['id']);


	//获取关于问题的回答和评论
	$orders = array('oldest', 'newest', 'votes');
	if (in_array($order, $orders))
		dr_get_question_reply($answers, $questions['id'], $order);
	else
		dr_get_question_reply($answers, $questions['id']);

	//分页处理
	$page_num = ceil($answers_num / $answer_page_size);
	dr_calc_pages($page, $page_num, $pages);

	$result_array[0] = $questions;
	$result_array[1] = $answers;
	$result_array[2] = $pages;

	if ($answers_num % $answer_page_size == 0 && $answers_num != 0) //在回答后，显示下一页，tpl中会用到此变量
		$result_array[3] = 1;
	else
		$result_array[3] = 0;
	return json_encode($result_array);
}


function dr_get_question_reply(&$answers, $question_id, $order = 'oldest')
{
	global $db;

	$page = $_POST['answer_page'];

	$answer_page_size = dr_db_get_option('answer_per_page');

	$answers_num = dr_db_read_one_value(dr_db_query_sub($db, 'select answers_num from ^questions where question_id=#', $question_id));
	if (($page - 1) * $answer_page_size > $answers_num || $page <= 0)
		$page = 1;
	$start = ($page - 1) * $answer_page_size;


	//读取回答和他相关的评论
	if ($order == 'oldest') //按时间最早的排序
	{
		$result = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_questions Q,dr_users U' .
									   ' where R.type=\'A\' and R.question_id=Q.question_id and R.user_id=U.user_id and R.question_id=#' .
									   ' and R.reply_id <> Q.best_answer order by updated_date asc limit #,#', $question_id, $start, $answer_page_size);
	}
	else if ($order == 'votes') //按投票数排序
	{
		$result = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_questions Q,dr_users U' .
									   ' where R.type=\'A\' and R.question_id=Q.question_id and R.user_id=U.user_id and R.question_id=#' .
									   ' and R.reply_id <> Q.best_answer order by up_votes_num desc,updated_date asc limit #,#', $question_id, $start, $answer_page_size);
	}
	else //按时间最近的排序
		$result = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_questions Q,dr_users U' .
									   ' where R.type=\'A\' and R.question_id=Q.question_id and R.user_id=U.user_id and R.question_id=#' .
									   ' and R.reply_id <> Q.best_answer order by updated_date desc limit #,#', $question_id, $start, $answer_page_size);

	while ($row = mysql_fetch_assoc($result))
	{

		$answer['id'] = $row['reply_id'];
		$answer['user_id'] = $row['user_id'];
		$answer['user_username'] = $row['username'];
		$answer['user_points'] = $row['points'];
		$answer['content'] = $row['content'];
		$answer['created_date'] = $row['created_date'];
		$answer['up_votes_num'] = $row['up_votes_num'];
		$answer['down_votes_num'] = $row['down_votes_num'];
		$answer['comments'] = array();

		//读取特定的回答的评论

		$result_ex = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_users U' .
										  ' where type=\'C\'and parent_id=# and R.user_id=U.user_id order by updated_date asc', $answer['id']);
		$answer['comment_num'] = mysql_num_rows($result_ex);
		while ($row_ex = mysql_fetch_assoc($result_ex))
		{
			$comment['id'] = $row_ex['reply_id'];
			$comment['user_id'] = $row_ex['user_id'];
			$comment['user_username'] = $row_ex['username'];
			$comment['content'] = $row_ex['content'];
			$comment['created_date'] = $row_ex['created_date'];
			$comment['updated_date'] = $row_ex['updated_date'];
			$comment['up_votes_num'] = $row_ex['up_votes_num'];
			array_push($answer['comments'], $comment);
		}

		array_push($answers, $answer);
	}
}

function dr_get_question_best_answer(&$answers, $question_id)
{
	global $db;
	$best_id = dr_db_read_one_value(dr_db_query_sub($db, 'select best_answer from ^questions where question_id=#', $question_id));
	if ($best_id != 0) //如果最佳答案存在
	{
		$result = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_users U' .
									   ' where R.user_id=U.user_id and R.reply_id=# order by updated_date asc', $best_id);
		if ($result == false)
			return;

		$row = mysql_fetch_assoc($result);

		$answer['id'] = $row['reply_id'];
		$answer['user_id'] = $row['user_id'];
		$answer['user_username'] = $row['username'];
		$answer['user_points'] = $row['points'];
		$answer['content'] = $row['content'];
		$answer['created_date'] = $row['created_date'];
		$answer['up_votes_num'] = $row['up_votes_num'];
		$answer['down_votes_num'] = $row['down_votes_num'];
		$answer['comments'] = array();

		//读取特定的回答的评论
		$result_ex = dr_db_query_sub($db, 'select R.*,U.username,U.email,U.points from dr_replies R,dr_users U' .
										  ' where type=\'C\'and parent_id=# and R.user_id=U.user_id order by updated_date asc', $answer['id']);
		$answer['comment_num'] = mysql_num_rows($result_ex);
		while ($row_ex = mysql_fetch_assoc($result_ex))
		{
			$comment['id'] = $row_ex['reply_id'];
			$comment['user_id'] = $row_ex['user_id'];
			$comment['user_username'] = $row_ex['username'];
			$comment['content'] = $row_ex['content'];
			$comment['created_date'] = $row_ex['created_date'];
			$comment['updated_date'] = $row_ex['updated_date'];
			$comment['up_votes_num'] = $row_ex['up_votes_num'];
			array_push($answer['comments'], $comment);
		}
		array_push($answers, $answer);
	}
}

/**
 * 标记某问题并关注之
 */
function dr_mark_question()
{
	global $db;

	$user_id = $_POST['user_id'];
	$question_id = $_POST['question_id'];
	$mark_type = $_POST['mark_type'];

	if ($mark_type == 'mark') {
		//将关注放入关注表中
		$result = dr_db_query_sub($db, 'insert into ^mark_question values(#,#,date_add(now(),interval 8 hour))', $question_id, $user_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将相应问题的关注度加一
		$result = dr_db_query_sub($db, 'update ^questions set marks_num=marks_num+1 where question_id=#', $question_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将关注行为放入历史记录
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,\'M\',date_add(NOW(),interval 8 hour),#)', $user_id, $question_id);
		if (!$result) {
			return '{"ret":0}';
		}

		/***************************发送消息给该用户的收听者******************************************/
		//		$listeners=dr_db_read_all_values(dr_db_query_sub($db, 'select user_id from ^mark_people where marked_user_id=#',$user_id));
		//		foreach ($listeners as $listener_id)
		//		{
		//			$result=dr_db_query_sub($db, 'insert into ^user_messages(user_id,sender_id,question_id,type,created_date)'.
		//				' values(#,#,#,\'MPM\',date_add(NOW(),interval 8 hour))',$listener_id,$user_id,$question_id);
		//		}
	} else if ($mark_type == 'cancel_mark') {
		//将关注放入关注表中
		$result = dr_db_query_sub($db, 'delete from ^mark_question where question_id=# and user_id=#', $question_id, $user_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将关注放入关注表中
		$result = dr_db_query_sub($db, 'update ^questions set marks_num=marks_num-1 where question_id=#', $question_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将关注行为放入历史记录
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,\'UM\',date_add(NOW(),interval 8 hour),#)', $user_id, $question_id);
		if (!$result) {
			return '{"ret":0}';
		}
	}

	return '{"ret":1}';
}

/**
 * 选择某问题的最佳答案
 *
 * @todo set best answers
 */
function dr_set_best_answer()
{
	global $db;

	$user_id = $_POST['user_id'];
	$question_id = $_POST['question_id'];
	$best_id = $_POST['best_id'];
	$set_type = $_POST['set_type'];

	if ($set_type == 'set_best') {
		$result = dr_db_query_sub($db, 'update ^questions set best_answer=# where question_id=#', $best_id, $question_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将动作加入到历史活动记录中
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,\'S\',date_add(NOW(),interval 8 hour),#)', $user_id, $best_id);
		if (!$result) {
			return '{"ret":0}';
		}

	}
	else if ($set_type == 'cancel_best') {
		$result = dr_db_query_sub($db, 'update ^questions set best_answer=0 where question_id=#', $question_id);
		if (!$result) {
			return '{"ret":0}';
		}

		//将动作加入到历史活动记录中
		$result = dr_db_query_sub($db, 'insert into ^action_history(user_id,action_type,action_date,object_id) values(#,\'US\',date_add(NOW(),interval 8 hour),#)', $user_id, $best_id);
		if (!$result) {
			return '{"ret":0}';
		}
	}

	return '{"ret":1}';
}

function dr_get_everyday_questionnum()
{
	global $db;
	$result_array = array();
	$display_days_num = dr_db_get_option('days_to_display', 30);
	for ($i = $display_days_num; $i >= 1; $i--)
	{
		$result = dr_db_query_sub($db, 'select date_format(date_sub(date_add(now(),interval 8 hour),interval # day),\'%Y-%m-%d\') as date,count(*) as question_num from dr_questions where' .
									   ' datediff(date_add(now(),interval 8 hour),updated_date)=#', $i, $i);
		$row = mysql_fetch_assoc($result);
		array_push($result_array, $row);
	}
	return json_encode($result_array);
}

/**
 * 获得查询的结果
 *
 * @return string
 */
function get_searched_questions_with_ids() {
	global $db;

	$ids = $_POST['ids'];

	if (empty($ids)) echo '';

	$sql = "SELECT Q.*,
			U.username AS user_username,
			U.email AS user_email,
			U.points AS user_points
		FROM ^questions Q, ^users U
		WHERE Q.question_id IN ($ids) AND Q.user_id = U.user_id";

	$result = dr_db_query_sub($db, $sql);

	$questions = array();
	while ($row = mysql_fetch_assoc($result)) {
		$questions[] = $row;
	}


	return json_encode($questions);
}

// end of file
